<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>非遗百科 - 探索中国非物质文化遗产</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
            padding: 0;
            margin: 0;
        }
        
        /* 头部导航栏样式 */
        .header {
            background-color: rgb(135, 73, 73);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            padding: 20px 25px;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0;
            z-index: 1001;
        }
        
        /* 左侧导航组 */
        .nav-left {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        
        /* 中间主题切换 */
        .nav-center {
            display: flex;
            align-items: center;
            flex: 1;
            justify-content: center;
        }
        
        /* 右侧用户设置 */
        .nav-right {
            display: flex;
            align-items: center;
        }
        
        /* 首页按钮样式 */
        .home-button {
            background-color: rgba(255, 255, 255, 0.2);
            padding: 8px 15px;
            border-radius: 20px;
            margin-right: 15px;
            transition: all 0.3s ease;
        }
        
        .home-button:hover {
            background-color: rgba(255, 255, 255, 0.3);
        }
        
        body.dark-mode .home-button {
            background-color: rgba(255, 255, 255, 0.1);
        }
        
        body.dark-mode .home-button:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }
        
        /* 模式切换按钮样式 */
        .theme-toggle {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #f0f0f0;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            margin-right: 15px;
        }
        
        .theme-toggle:hover {
            background-color: #e0e0e0;
            transform: rotate(15deg);
        }
        
        .theme-toggle svg {
            width: 20px;
            height: 20px;
            fill: #666;
        }
        
        /* 暗色模式样式 */
        body.dark-mode {
            background-color: #1a1a1a;
            color: #e0e0e0;
        }
        
        body.dark-mode .header {
            background-color: #2a2a2a;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
        }
        
        body.dark-mode .category-title {
            background-color: #3a3a3a;
            color: #e0e0e0;
        }
        
        body.dark-mode .category-title:hover {
            background-color: #4a4a4a;
        }
        
        body.dark-mode .category-dropdown {
            background-color: #2a2a2a;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
        }
        
        body.dark-mode .category-item {
            color: #e0e0e0;
        }
        
        body.dark-mode .category-item:hover {
            background-color: #3a3a3a;
        }
        
        body.dark-mode .user-avatar {
            background-color: #3a3a3a;
        }
        
        body.dark-mode .user-avatar:hover {
            background-color: #4a4a4a;
        }
        
        body.dark-mode .user-avatar.visitor::after {
            color: #999;
        }
        
        body.dark-mode .content-container h1 {
            color: #e0e0e0;
        }
        
        body.dark-mode .search-container {
            background-color: #2a2a2a;
            border-radius: 25px;
            padding: 5px;
        }
        
        body.dark-mode #search-input {
            background-color: #3a3a3a;
            border-color: #4a4a4a;
            color: #e0e0e0;
        }
        
        body.dark-mode #search-input:focus {
            border-color: #4CAF50;
        }
        
        body.dark-mode .history-container {
            background-color: #2a2a2a;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
        }
        
        body.dark-mode .history-header {
            color: #999;
        }
        
        body.dark-mode .history-tag {
            background-color: #3a3a3a;
            color: #e0e0e0;
        }
        
        body.dark-mode .history-tag:hover {
            background-color: #4a4a4a;
        }
        
        body.dark-mode .section-title {
            color: #e0e0e0;
            border-bottom-color: #4CAF50;
        }
        
        body.dark-mode .pin {
            background-color: #2a2a2a;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        }
        
        body.dark-mode .pin:hover {
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.5);
        }
        
        body.dark-mode .pin-title {
            color: #e0e0e0;
        }
        
        body.dark-mode .pin-desc {
            color: #999;
        }
        
        body.dark-mode #loading-indicator {
            color: #999;
        }
        
        body.dark-mode .no-results {
            color: #666;
        }
        
        body.dark-mode .theme-toggle {
            background-color: #3a3a3a;
        }
        
        body.dark-mode .theme-toggle:hover {
            background-color: #4a4a4a;
        }
        
        body.dark-mode .theme-toggle svg {
            fill: #e0e0e0;
        }
        
        .header-left {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            gap: 10px;
        }
        
        .header-right {
            display: flex;
            align-items: center;
        }
        
         
        
        /* 类别目录栏样式 */
        .category-nav {
            position: relative;
            cursor: pointer;
        }
        
        .category-title {
            padding: 8px 16px;
            background-color: #f0f0f0;
            border-radius: 6px;
            font-size: 14px;
            color: #333;
            transition: all 0.3s ease;
        }
        
        .category-title:hover {
            background-color: #e0e0e0;
        }
        
        .category-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            padding: 10px 0;
            min-width: 150px;
            display: none;
            margin-top: 5px;
        }
        
        .category-nav:hover .category-dropdown {
            display: block;
        }
        
        .category-item {
            padding: 10px 20px;
            font-size: 14px;
            color: #333;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        
        .category-item:hover {
            background-color: #f0f0f0;
        }
        
        /* 内容容器样式 */
        .content-container {
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }

        h1 {
            text-align: center;
            margin-bottom: 30px;
            color: #333;
        }

        .waterfall-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
        }

        /* 搜索栏样式 */
        .search-container {
            width: 100%;
            max-width: 600px;
            margin-bottom: 20px;
            position: relative;
        }

        .search-bar {
            display: flex;
            position: relative;
        }

        #search-input {
            flex: 1;
            padding: 12px 20px;
            font-size: 16px;
            border: 2px solid #ddd;
            border-radius: 25px 0 0 25px;
            outline: none;
            transition: border-color 0.3s ease;
        }

        #search-input:focus {
            border-color: #4CAF50;
        }

        #search-button {
            padding: 12px 24px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 0 25px 25px 0;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        #search-button:hover {
            background-color: #45a049;
        }

        /* 历史记录样式 - 内嵌在搜索栏中 */
        .history-container {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background-color: white;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            display: none;
            margin-top: 5px;
        }

        .history-container.show {
            display: block;
        }

        .history-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            font-weight: 600;
            color: #666;
        }

        #clear-history {
            background: none;
            border: none;
            color: #4CAF50;
            cursor: pointer;
            font-size: 14px;
            padding: 0;
            transition: color 0.3s ease;
        }

        #clear-history:hover {
            color: #45a049;
        }

        .history-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        .history-tag {
            display: flex;
            align-items: center;
            padding: 6px 12px;
            background-color: #f0f0f0;
            border-radius: 15px;
            font-size: 14px;
            color: #333;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .history-tag:hover {
            background-color: #e0e0e0;
        }

        .history-tag-remove {
            margin-left: 8px;
            font-size: 16px;
            color: #999;
            transition: color 0.3s ease;
        }

        .history-tag-remove:hover {
            color: #666;
        }

        /* 搜索结果样式 */
        .search-results {
            width: 100%;
            margin-bottom: 20px;
            display: none;
        }

        .search-results.show {
            display: block;
        }

        .no-results {
            text-align: center;
            padding: 40px 20px;
            color: #999;
            font-size: 16px;
        }

        /* 推荐内容样式 */
        .recommended-content {
            width: 100%;
            margin-bottom: 20px;
        }

        .section-title {
            font-size: 20px;
            font-weight: 600;
            color: #333;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #4CAF50;
        }

        /* 瀑布流样式 */
        .waterfall {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
            width: 100%;
        }

        .recommended-waterfall {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
            width: 100%;
        }

        .pin {
            background-color: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .pin:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
        }

        .pin img {
            width: 100%;
            height: auto;
            display: block;
        }

        .pin-content {
            padding: 15px;
        }

        .pin-title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
        }

        .pin-desc {
            font-size: 14px;
            color: #666;
            line-height: 1.5;
        }

        #loading-indicator {
            margin-top: 20px;
            text-align: center;
            font-size: 14px;
            color: #666;
            padding: 20px;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .waterfall {
                grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
                gap: 15px;
            }

            body {
                padding: 10px;
            }
        }

        @media (max-width: 480px) {
            .waterfall {
                grid-template-columns: 1fr;
            }
        }
        
        /* 用户头像样式 */
        .avatar-container {
            position: relative;
            margin-right: 15px;
        }
        
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #f0f0f0;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            overflow: hidden;
        }
        
        .user-avatar:hover {
            transform: scale(1.1);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        }
        
        .avatar-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .avatar-menu {
            position: absolute;
            top: 100%;
            right: 0;
            margin-top: 10px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            overflow: hidden;
            z-index: 1002;
            display: none;
            min-width: 120px;
        }
        
        .avatar-container:hover .avatar-menu {
            display: block;
        }
        
        .avatar-menu-item {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            color: #333;
            text-decoration: none;
            transition: background-color 0.3s ease;
        }
        
        .avatar-menu-item:hover {
            background-color: #f5f5f5;
        }
        
        .menu-icon {
            margin-right: 10px;
            font-size: 16px;
        }
        
        .menu-text {
            font-size: 14px;
        }
        
        /* 暗色模式适配 */
        body.dark-mode .user-avatar {
            background-color: #3a3a3a;
        }
        
        body.dark-mode .avatar-menu {
            background-color: #2a2a2a;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
        }
        
        body.dark-mode .avatar-menu-item {
            color: #e0e0e0;
        }
        
        body.dark-mode .avatar-menu-item:hover {
            background-color: #3a3a3a;
        }
    </style>
    <script src="assets/js/avatarMenu.js"></script>
</head>
<body>
    <!-- 头部导航栏 -->
    <header class="header">
        <!-- 左侧导航组 -->
        <div class="nav-left">
            <!-- 首页按钮 -->
            <div class="home-button">
                <a href="index.html" style="display: flex; align-items: center; text-decoration: none; color: white;">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 5px;">
                        <path d="M12 3L2 12h3v8h6v-6h4v6h6v-8h3L12 3z"/>
                    </svg>
                    <span>首页</span>
                </a>
            </div>
            
            <!-- 类别目录栏 -->
            <div class="category-nav">
                <div class="category-title">非遗类别</div>
                <div class="category-dropdown">
                    <div class="category-item" data-category="传统技艺">传统技艺</div>
                    <div class="category-item" data-category="传统舞蹈">传统舞蹈</div>
                    <div class="category-item" data-category="传统音乐">传统音乐</div>
                    <div class="category-item" data-category="传统戏剧">传统戏剧</div>
                    <div class="category-item" data-category="民间美术">民间美术</div>
                    <div class="category-item" data-category="传统医药">传统医药</div>
                    <div class="category-item" data-category="传统体育">传统体育</div>
                    <div class="category-item" data-category="民俗活动">民俗活动</div>
                    <div class="category-item" data-category="传统文学">传统文学</div>
                    <div class="category-item" data-category="传统手工艺">传统手工艺</div>
                </div>
            </div>
        </div>
        
        <!-- 中间主题切换 -->
        <div class="nav-center">
            <button class="theme-toggle" id="theme-toggle">
                <svg viewBox="0 0 24 24">
                    <path d="M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9 9-4.03 9-9-4.03-9-9-9zm0 16c-3.86 0-7-3.14-7-7s3.14-7 7-7 7 3.14 7 7-3.14 7-7 7z"/>
                    <path d="M12 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/>
                </svg>
            </button>
        </div>
        
        <!-- 右侧用户设置 -->
        <div class="nav-right">
            <!-- 用户头像功能已移除 -->
        </div>
    </header>
    
    <!-- 主要内容区域 -->
    <div class="content-container">
        <h1>非遗百科 - 探索中国非物质文化遗产</h1>
        
        <div class="waterfall-container">
        <!-- 搜索栏和历史记录 -->
        <div class="search-container">
            <div class="search-bar">
                <input type="text" id="search-input" placeholder="搜索图片关键词...">
                <button id="search-button">搜索</button>
            </div>
            <div class="history-container">
                <div class="history-header">
                    <span>搜索历史</span>
                    <button id="clear-history">清空</button>
                </div>
                <div class="history-tags" id="history-tags">
                    <!-- 历史搜索标签会在这里动态生成 -->
                </div>
            </div>
        </div>
        
        <!-- 搜索结果区域 -->
        <div class="search-results" id="search-results">
            <div class="section-title">搜索结果</div>
            <div class="waterfall" id="waterfall"></div>
            <div id="no-results" class="no-results" style="display: none;">
                <p>暂无该内容</p>
            </div>
        </div>
        
        <!-- 推荐内容区域 -->
        <div class="recommended-content">
            <div class="section-title">推荐内容</div>
            <div class="recommended-waterfall" id="recommended-waterfall"></div>
        </div>
        
        <div id="loading-indicator" style="display: none;">
            <p>加载中...</p>
        </div>
    </div>
    
    <script>
        // 类别目录栏点击事件处理
        document.querySelectorAll('.category-item').forEach(item => {
            item.addEventListener('click', function() {
                const category = this.getAttribute('data-category');
                window.location.href = `category.html?type=${encodeURIComponent(category)}`;
            });
        });
        
         
        
        // 为页面标题添加点击事件，跳转到首页
        document.querySelector('h1').addEventListener('click', function() {
            window.location.href = 'index.html';
        });
        
        // 模式切换功能
        function setupThemeToggle() {
            const themeToggle = document.getElementById('theme-toggle');
            const body = document.body;
            
            // 检查本地存储中的主题偏好
            const savedTheme = localStorage.getItem('theme');
            if (savedTheme === 'dark') {
                body.classList.add('dark-mode');
                updateThemeIcon(true);
            }
            
            // 模式切换点击事件
            themeToggle.addEventListener('click', function() {
                const isDark = body.classList.toggle('dark-mode');
                
                // 保存主题偏好到本地存储
                localStorage.setItem('theme', isDark ? 'dark' : 'light');
                
                // 更新图标
                updateThemeIcon(isDark);
            });
            
            // 更新主题图标
            function updateThemeIcon(isDark) {
                const svg = themeToggle.querySelector('svg');
                if (isDark) {
                    // 深色模式 - 显示太阳图标
                    svg.innerHTML = '<path d="M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zm0-5c-3.87 0-7 3.13-7 7s3.13 7 7 7 7-3.13 7-7-3.13-7-7-7zm0 17c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/>';
                } else {
                    // 浅色模式 - 显示月亮图标
                    svg.innerHTML = '<path d="M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9 9-4.03 9-9-4.03-9-9-9zm0 16c-3.86 0-7-3.14-7-7s3.14-7 7-7 7 3.14 7 7-3.14 7-7 7z"/><path d="M12 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/>';
                }
            }
        }
        
        // 初始化主题切换功能
        setupThemeToggle();
        // 示例数据 - 非遗相关分类
        const imageCategories = [
            "传统技艺", "传统舞蹈", "传统音乐", "传统戏剧", "民间美术",
            "传统医药", "传统体育", "民俗活动", "传统文学", "传统手工艺"
        ];
        
        // 推荐内容数据（固定ID，避免与主内容重复）
        const recommendedIds = [101, 102, 103, 104, 105, 106, 107, 108];
        
        // 非遗相关内容数组（标题和描述一一对应）
        const heritageItems = [
            { title: "京剧表演艺术", description: "京剧是中国五大戏曲剧种之一，形成于北京，被誉为中国的国粹和第一大剧种。" },
            { title: "苏州园林营造技艺", description: "苏州园林是中国古典园林的代表，以其精湛的造园技艺和独特的艺术风格闻名于世。" },
            { title: "中国剪纸艺术", description: "剪纸是中国传统民间艺术，以纸为载体，通过剪、刻等手法创作各种图案和形象。" },
            { title: "茅台酒酿制技艺", description: "茅台酒酿制技艺是中国白酒酿造的典范，具有悠久的历史和独特的工艺特色。" },
            { title: "中医针灸疗法", description: "中医针灸是中国传统医学的重要组成部分，通过刺激人体穴位达到治疗和保健的目的。" },
            { title: "端午节习俗", description: "端午节是中国传统节日，有着丰富的民俗活动和深厚的文化内涵。" },
            { title: "昆曲表演艺术", description: "昆曲是中国最古老的戏曲剧种之一，被称为'百戏之祖'，是中国戏曲艺术的瑰宝。" },
            { title: "中国书法艺术", description: "中国书法是一门独特的艺术形式，通过毛笔书写汉字，展现线条美感和文化内涵。" },
            { title: "龙泉青瓷烧制技艺", description: "龙泉青瓷烧制技艺历史悠久，产品以'青如玉、明如镜、薄如纸、声如磬'著称。" },
            { title: "太极拳表演", description: "太极拳是中国传统武术和养生方法，融合了中国传统哲学思想和武术精髓。" }
        ];
        
        // 为了保持向后兼容，创建titles和descriptions数组的引用
        const titles = heritageItems.map(item => item.title);
        const descriptions = heritageItems.map(item => item.description);
        
        // 图片ID计数器
        let imageId = 1;
        // 每次加载的数量
        const loadCount = 12;
        // 最大图片ID
        const maxImageId = 100;
        
        // 推荐内容已加载标志
        let recommendedLoaded = false;
        // 已使用的推荐内容索引
        const usedRecommendedIndices = [];
        
        // 获取随机数据
        function getRandomData() {
            const category = imageCategories[Math.floor(Math.random() * imageCategories.length)];
            const title = titles[Math.floor(Math.random() * titles.length)];
            const description = descriptions[Math.floor(Math.random() * descriptions.length)];
            
            // 随机高度（200-400之间）
            const height = Math.floor(Math.random() * 200) + 200;
            
            // 使用picsum.photos服务获取随机图片，并确保URL参数正确编码
            const imageUrl = `https://picsum.photos/id/${imageId++}/${400}/${height}`;
            
            return { imageUrl, title, description, category };
        }
        
        // 获取推荐内容数据（确保不重复）
        function getRecommendedData() {
            // 如果所有项目都已使用，则重置已使用索引数组
            if (usedRecommendedIndices.length >= heritageItems.length) {
                usedRecommendedIndices.length = 0;
            }
            
            // 从未使用的索引中随机选择一个
            let randomIndex;
            do {
                randomIndex = Math.floor(Math.random() * heritageItems.length);
            } while (usedRecommendedIndices.includes(randomIndex));
            
            // 记录已使用的索引
            usedRecommendedIndices.push(randomIndex);
            
            const id = recommendedIds[Math.floor(Math.random() * recommendedIds.length)];
            const category = imageCategories[Math.floor(Math.random() * imageCategories.length)];
            
            // 使用选定的非遗项目
            const item = heritageItems[randomIndex];
            
            // 随机高度（200-400之间）
            const height = Math.floor(Math.random() * 200) + 200;
            
            // 使用picsum.photos服务获取随机图片，并确保URL参数正确编码
            const imageUrl = `https://picsum.photos/id/${id}/${400}/${height}`;
            
            return { imageUrl, title: item.title, description: item.description, category };
        }
        
        // 加载推荐内容
        function loadRecommendedContent() {
            if (recommendedLoaded) return;
            
            const recommendedWaterfall = document.getElementById('recommended-waterfall');
            
            // 加载8个推荐内容
            for (let i = 0; i < 8; i++) {
                const data = getRecommendedData();
                const pin = createPin(data);
                recommendedWaterfall.appendChild(pin);
            }
            
            recommendedLoaded = true;
        }
        
        // 创建瀑布流项目
        function createPin(data) {
            const pin = document.createElement('div');
            pin.className = 'pin';
            
            pin.innerHTML = `
                <img src="${data.imageUrl}" alt="${data.title}">
                <div class="pin-content">
                    <h3 class="pin-title">${data.title}</h3>
                    <p class="pin-desc">${data.description}</p>
                </div>
            `;
            
            // 添加点击跳转功能
            pin.addEventListener('click', () => {
                // 在实际项目中，这里应该跳转到对应的详情页面
                // 由于是演示，我们使用alert来模拟跳转
                alert(`跳转到"${data.title}"的详情页面`);
                // 实际项目中的跳转代码可能是这样的：
                // window.location.href = `detail.html?id=${data.id}&title=${encodeURIComponent(data.title)}`;
            });
            
            return pin;
        }
        
        // 检查是否滚动到页面底部
        function isScrolledToBottom() {
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
            const clientHeight = document.documentElement.clientHeight || window.innerHeight;
            
            // 当滚动到距离底部100px时触发加载
            return scrollTop + clientHeight >= scrollHeight - 100;
        }
        
        // 滚动事件处理函数
        let isLoading = false;
        let debounceTimer;
        
        function handleScroll() {
            // 防抖，避免频繁触发
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                if (isScrolledToBottom() && !isLoading) {
                    // 根据不同模式使用不同的加载条件
                    if (isSearchMode) {
                        const waterfall = document.getElementById('waterfall');
                        if (waterfall.children.length < filteredPins.length) {
                            // 临时移除监听，避免重复触发
                            window.removeEventListener('scroll', handleScroll);
                            loadMore();
                        }
                    } else if (imageId <= maxImageId) {
                        // 临时移除监听，避免重复触发
                        window.removeEventListener('scroll', handleScroll);
                        loadMore();
                    }
                }
            }, 200);
        }
        
        // 搜索历史管理
        const MAX_HISTORY_SIZE = 10;
        let searchHistory = JSON.parse(localStorage.getItem('searchHistory')) || [];
        let isSearchMode = false; // 是否处于搜索模式
        let currentSearchTerm = ''; // 当前搜索关键词
        let filteredPins = []; // 搜索结果
        
        // 保存搜索历史到localStorage
        function saveSearchHistory() {
            localStorage.setItem('searchHistory', JSON.stringify(searchHistory));
        }
        
        // 添加搜索历史
        function addToSearchHistory(term) {
            // 去除首尾空格
            term = term.trim();
            if (!term) return;
            
            // 如果已存在，则移除旧的
            const index = searchHistory.indexOf(term);
            if (index > -1) {
                searchHistory.splice(index, 1);
            }
            
            // 添加到开头
            searchHistory.unshift(term);
            
            // 限制历史记录数量
            if (searchHistory.length > MAX_HISTORY_SIZE) {
                searchHistory.pop();
            }
            
            // 保存并更新UI
            saveSearchHistory();
            renderSearchHistory();
        }
        
        // 从搜索历史中移除
        function removeFromSearchHistory(term) {
            const index = searchHistory.indexOf(term);
            if (index > -1) {
                searchHistory.splice(index, 1);
                saveSearchHistory();
                renderSearchHistory();
            }
        }
        
        // 清空搜索历史
        function clearSearchHistory() {
            searchHistory = [];
            saveSearchHistory();
            renderSearchHistory();
        }
        
        // 渲染搜索历史
        function renderSearchHistory() {
            const historyTags = document.getElementById('history-tags');
            historyTags.innerHTML = '';
            
            if (searchHistory.length === 0) {
                historyTags.innerHTML = '<span style="color: #999; font-size: 14px;">暂无搜索历史</span>';
                return;
            }
            
            searchHistory.forEach(term => {
                const tag = document.createElement('div');
                tag.className = 'history-tag';
                
                const textSpan = document.createElement('span');
                textSpan.textContent = term;
                textSpan.addEventListener('click', () => {
                    performSearch(term);
                });
                
                const removeSpan = document.createElement('span');
                removeSpan.className = 'history-tag-remove';
                removeSpan.textContent = '×';
                removeSpan.addEventListener('click', (e) => {
                    e.stopPropagation(); // 阻止事件冒泡
                    removeFromSearchHistory(term);
                });
                
                tag.appendChild(textSpan);
                tag.appendChild(removeSpan);
                historyTags.appendChild(tag);
            });
        }
        
        // 执行搜索
        function performSearch(term) {
            term = term.toLowerCase().trim();
            if (!term) return;
            
            // 更新搜索框
            document.getElementById('search-input').value = term;
            
            // 添加到搜索历史
            addToSearchHistory(term);
            
            // 标记为搜索模式
            isSearchMode = true;
            currentSearchTerm = term;
            
            // 显示搜索结果区域
            const searchResults = document.getElementById('search-results');
            searchResults.classList.add('show');
            
            // 清空瀑布流
            const waterfall = document.getElementById('waterfall');
            waterfall.innerHTML = '';
            
            // 隐藏无结果提示和加载指示器
            document.getElementById('no-results').style.display = 'none';
            document.getElementById('loading-indicator').style.display = 'none';
            
            // 生成搜索结果
            const allData = [];
            for (let i = 1; i <= maxImageId; i++) {
                const category = imageCategories[Math.floor(Math.random() * imageCategories.length)];
                
                // 从heritageItems数组中随机选择一项，确保标题和描述对应
                const item = heritageItems[Math.floor(Math.random() * heritageItems.length)];
                
                allData.push({ id: i, category, title: item.title, description: item.description });
            }
            
            // 过滤数据
            filteredPins = allData.filter(item => 
                item.category.toLowerCase().includes(term) ||
                item.title.toLowerCase().includes(term) ||
                item.description.toLowerCase().includes(term)
            );
            
            // 检查是否有搜索结果
            if (filteredPins.length === 0) {
                document.getElementById('no-results').style.display = 'block';
                return;
            }
            
            // 显示搜索结果
            const displayCount = Math.min(loadCount, filteredPins.length);
            for (let i = 0; i < displayCount; i++) {
                const data = filteredPins[i];
                const height = Math.floor(Math.random() * 200) + 200;
                // 不使用category作为URL参数，避免中文字符编码问题
                const imageUrl = `https://picsum.photos/id/${data.id}/${400}/${height}`;
                
                const pin = createPin({ imageUrl, title: data.title, description: data.description, category: data.category });
                waterfall.appendChild(pin);
            }
        }
        
        // 加载更多搜索结果
        function loadMoreSearchResults() {
            if (!isSearchMode) return;
            
            const searchResults = document.getElementById('search-results');
            const waterfall = document.getElementById('waterfall');
            const currentCount = waterfall.children.length;
            
            // 检查是否还有更多结果
            if (currentCount >= filteredPins.length) {
                window.removeEventListener('scroll', handleScroll);
                return;
            }
            
            // 显示加载状态
            const loadingIndicator = document.getElementById('loading-indicator');
            loadingIndicator.style.display = 'block';
            
            // 模拟网络加载延迟
            setTimeout(() => {
                // 加载更多结果
                const endIndex = Math.min(currentCount + loadCount, filteredPins.length);
                for (let i = currentCount; i < endIndex; i++) {
                    const data = filteredPins[i];
                    const height = Math.floor(Math.random() * 200) + 200;
                    // 不使用category作为URL参数，避免中文字符编码问题
                    const imageUrl = `https://picsum.photos/id/${data.id}/${400}/${height}`;
                    
                    const pin = createPin({ imageUrl, title: data.title, description: data.description, category: data.category });
                    waterfall.appendChild(pin);
                }
                
                // 隐藏加载指示器
                loadingIndicator.style.display = 'none';
                
                // 如果还有更多结果，继续监听滚动事件
                if (waterfall.children.length < filteredPins.length) {
                    window.addEventListener('scroll', handleScroll);
                }
            }, 800);
        }
        
        // 加载更多内容（根据模式选择）
        function loadMore() {
            if (isSearchMode) {
                loadMoreSearchResults();
            } else {
                // 在非搜索模式下，我们不加载主瀑布流内容，因为推荐内容区域已经始终展示
                // 这里保持原有逻辑但不实际加载内容，以避免影响页面结构
                window.removeEventListener('scroll', handleScroll);
            }
        }
        
        // 获取URL参数
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.search);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
        }
        
        // 初始加载
        document.addEventListener('DOMContentLoaded', () => {
            // 加载推荐内容
            loadRecommendedContent();
            
            // 渲染搜索历史
            renderSearchHistory();
            
            // 添加滚动事件监听
            window.addEventListener('scroll', handleScroll);
            
            // 检查URL是否包含搜索参数
            const searchParam = getUrlParameter('search');
            if (searchParam) {
                performSearch(searchParam);
                // 隐藏历史记录
                document.querySelector('.history-container').classList.remove('show');
            }
            
            // 搜索按钮点击事件
            document.getElementById('search-button').addEventListener('click', () => {
                const term = document.getElementById('search-input').value;
                performSearch(term);
                // 点击搜索后隐藏历史记录
                document.querySelector('.history-container').classList.remove('show');
            });
            
            // 搜索框回车事件
            document.getElementById('search-input').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    const term = document.getElementById('search-input').value;
                    performSearch(term);
                    // 回车搜索后隐藏历史记录
                    document.querySelector('.history-container').classList.remove('show');
                }
            });
            
            // 清空历史记录按钮点击事件
            document.getElementById('clear-history').addEventListener('click', clearSearchHistory);
            
            // 搜索框输入事件 - 显示搜索历史
            const searchInput = document.getElementById('search-input');
            const historyContainer = document.querySelector('.history-container');
            
            searchInput.addEventListener('focus', () => {
                if (searchHistory.length > 0) {
                    historyContainer.classList.add('show');
                }
            });
            
            searchInput.addEventListener('input', () => {
                if (searchInput.value.trim() === '' && searchHistory.length > 0) {
                    historyContainer.classList.add('show');
                } else {
                    historyContainer.classList.remove('show');
                }
            });
            
            // 点击搜索框外部隐藏历史记录
            document.addEventListener('click', (e) => {
                if (!searchInput.contains(e.target) && !historyContainer.contains(e.target) && 
                    e.target !== document.getElementById('search-button')) {
                    historyContainer.classList.remove('show');
                }
            });
        });
    </script>
</body>
</html>